<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      function Node(val) {
        this.val = val;
        this.left = null;
        this.right = null;
      }
      var a = new Node(1);
      var b = new Node(2);
      var c = new Node(2);
      var d = new Node(3);
      var e = new Node(3);
      var f = new Node(4);
      var g = new Node(4);
      a.left = b
      a.right = c;
      b.left = d;
      b.right = e;
      d.left = f
      d.right = g
      // 求高度，从下往上，后序遍历
      const getDepth = (node) => {
        // 节点为null，返回高度0
        if (!node) {
          return 0
        }
        // 左子树
        let leftNum = getDepth(node.left)
        if (leftNum === -1) {
          return -1
        }
        // 右子树
        let rightNum = getDepth(node.right)
        if (rightNum === -1) {
          return -1
        }

        // 判断高度差
        if (Math.abs(leftNum - rightNum) > 1) {
          return -1
        } else {
          return 1 + Math.max(leftNum, rightNum)
        }
      };
      const isBalanced = (root) => {
        if (!root) return true
        // 若是-1，则高度差大于1,就不是平衡二叉树
        return getDepth(root) === -1 ? false : true
      };

      console.log(isBalanced(a));
    </script>
  </body>
</html>
